home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2946 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.2 KB  |  52 lines

  1. Path: alpnet76.alpes-net.fr!utilisateur
  2. From: monnet@alpes-net.fr (Nicolas Monnet)
  3. Newsgroups: comp.lang.c++
  4. Subject: [Q] new-allocated objects within try block
  5. Date: Sat, 20 Jan 1996 21:47:21 +0100
  6. Organization: Ensieg/I.N.P.G.
  7. Message-ID: <monnet-2001962147210001@alpnet76.alpes-net.fr>
  8. NNTP-Posting-Host: alpnet76.alpes-net.fr
  9.  
  10. Here's the problem I'm facing -- it's probably a bad approach, it's even
  11. possibly answered in some faq but...
  12.  
  13. I need to allocate an object with new, and delete it in the same block, 
  14. as if it was allocated on the stack.
  15. Why? Well, I'm using an abstract base class, and I have different descendents,
  16. and, of course, I create one of them. Example:
  17.  
  18. class ABC { public: virtual void DoSomething() = 0; };
  19. class A : public ABC { public: virtual void DoSomething(); };
  20. class B : public ABC { public: virtual void DoSomething(); };
  21.  
  22. (...)
  23. try {
  24.    ABC *p;
  25.    if (test) {
  26.      ..
  27.      p = new A;
  28.    } else {
  29.       ...
  30.       p = new B;
  31.    }
  32.    ...
  33.    throw sthg;
  34.    ...
  35.    p->DoSomething();
  36.    delete p;
  37. } catch (...) {
  38.  
  39. }
  40.  
  41. Then, *p is not properly destroyed, isn't it?
  42.  
  43. What is another way of doing it?
  44.  
  45.  
  46.  
  47. Thanks in advance!
  48.  
  49. ----
  50. Nicolas Monnet
  51. Monnet@alpes-net.fr
  52.